/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */
package com.jav;

import com.jav.bean.Cliente;
import com.jav.bean.Pedido;
import com.jav.bean.Producto;
import com.jav.bean.Productos;
import com.jav.inter.Constantes;
import com.jav.per.PersisPedido;
import com.jav.per.PersisProducto;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.jav.util.FileInfo;
import com.jav.util.HttpMultipartRequest;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.util.Resources;
import java.util.Enumeration;
import java.util.Hashtable;

public class CapturaForm extends Form implements Constantes {

    private Button bt_producto;
    private Button bt_des = createButton();
    private Button bt_prec = createButton();
    private Button bt_subTo = createButton();
    private Label lb_graTo = new Label("");
    private Label lb_totCamb = new Label("");
    private final String INPUTMODE = "123";
    private TextField tf_cant = new TextField("");
    private TextField tf_camb = new TextField("");
    private Pedido pedido = new Pedido();
    private Producto prodSelect;
    private Button bt_subtotal;
    private Button bt_addCar;
    private Button footer;
    private Image imgError;
    private static final VentanaEspera waiting = new VentanaEspera("CARGANDO...");
    private int consecPedido = 0;

    public CapturaForm(Cliente cliente) {
        super("CAPTURA");
        Resources res = null;
        try {
            pedido.setCliente(cliente);
            setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            tf_cant.setInputMode(INPUTMODE);
            tf_cant.setFocus(true);
            tf_camb.setInputMode(INPUTMODE);
            tf_cant.setConstraint(TextField.NUMERIC);
            tf_camb.setConstraint(TextField.NUMERIC);
            lb_graTo.setAlignment(CENTER);
            lb_totCamb.setAlignment(CENTER);
            bt_subTo.setFocusable(false);

            res = Datos.getInstance().getRes();

            imgError = res.getImage("cancel.png");

            bt_subtotal = new Button("Subtotal");
            bt_subtotal.setAlignment(CENTER);


            bt_producto = new Button("(+)Producto", res.getImage("adBrowser.png"));
            bt_producto.setFocusable(true);
            bt_producto.setAlignment(CENTER);
            bt_producto.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    ProductosDialog.getInstance().show();
                    prodSelect = ProductosDialog.proselect;
                    if (prodSelect != null) {
                        bt_des.setText(prodSelect.getDes());
                        bt_prec.setText("$ " + prodSelect.getPrecio());
                        tf_cant.requestFocus();
                    } else {
                        bt_des.setText("");
                        bt_prec.setText("");
                        bt_producto.requestFocus();
                    }

                }
            });



            bt_subtotal.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    if (prodSelect != null) {
                        long sub = 0;
                        try {
                            //sub = Float.parseFloat(tf_cant.getText());
                            sub = Long.parseLong(tf_cant.getText());
                        } catch (Exception e) {
                            sub = 0;
                        }
                        //bt_subTo.setText("$ " + String.valueOf(Float.parseFloat(prodSelect.getPrecio())*sub));
                        bt_subTo.setText("$ " + String.valueOf(Long.parseLong(prodSelect.getPrecio()) * sub));

                    }
                }
            });

            bt_addCar = new Button("Agregar", res.getImage("car"));
            bt_addCar.setAlignment(CENTER);

            bt_addCar.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    if (prodSelect != null) {
                        int cant = 0;
                        int camb = 0;
                        try {
                            //camb = Float.parseFloat(tf_camb.getText());
                            camb = Integer.parseInt(tf_camb.getText());
                        } catch (Exception e) {
                            camb = 0;
                        }
                        try {
                            //cant = Float.parseFloat(tf_cant.getText());
                            cant = Integer.parseInt(tf_cant.getText());
                        } catch (Exception e) {
                            cant = 0;
                        }

                        if ((cant >= 0 || camb >= 0) && (cant + camb > 0)) {

                            pedido.addProd(cant, camb, prodSelect);
                            upadte();
                            prodSelect = null;
                            tf_cant.setText("");
                            tf_camb.setText("");
                            bt_subTo.setText("");
                            bt_des.setText("");
                            bt_prec.setText("");
                            bt_producto.requestFocus();

                        }


                    } else {
                        Command okCommand = new Command("OK");
                        Dialog.show("ERROR", "Debe adicionar primero un producto",
                                okCommand, new Command[]{okCommand}, Dialog.TYPE_INFO, imgError, 0, null);
                    }
                }
            });


            // Container ct2 = new Container(new GridLayout(1, 2));
            // ct2.addComponent(createPair("Pre: ", bt_prec, largestW));
            // ct2.addComponent(bt_subtotal);


            addComponent(bt_producto);
            Container largest = createPair("Des: ", bt_des, 30);
            int largestW = largest.getComponentAt(0).getPreferredW();

            // addComponent(ct2);

            addComponent(createPair("Cantidad: ", tf_cant, largestW));
            addComponent(createPair("Cambios: ", tf_camb, largestW));
            addComponent(bt_addCar);

            //addComponent(createPair("SUBTOTAL: ", bt_subTo, largestW));
            bt_subtotal.setAlignment(CENTER);
            addComponent(createSub(bt_subTo, bt_subtotal));

            addComponent(largest);
            addComponent(createPair("Pre: ", bt_prec, largestW));


            addComponent(createPair("$ TOT: $", lb_graTo, largestW));
            addComponent(createPair("$ CAM: $", lb_totCamb, largestW));


            addCommand(new Command("Guardar", res.getImage("download_cover.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (pedido != null && pedido.getVp() != null && !pedido.getVp().isEmpty()) {

                        consecPedido = Datos.getInstance().getMaxPedido();


                        new Thread(new Runnable() {

                            public void run() {

                                removeAllCommands();
                                try {
                                    //Persistencia.delete("PEDIDOS");
                                    PersisPedido pd = new PersisPedido();
                                    //consecPedido = pd.getConsec();
                                    pd.setNumero(consecPedido);
                                    pd.setCliente(pedido.getCliente().getCodigo());
                                    pd.setDt_inicio();
                                    pd.setVenta(pedido.getTotalPedido());
                                    pd.setCambio(pedido.getTotalCambios());
                                    Persistencia p = new Persistencia(PERS_PEDIDO);
                                    p.save(pd.persist());
                                    Datos.getInstance().setMaxPedido(consecPedido);


                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                                try {
                                    Enumeration e = pedido.getVp().elements();
                                    while (e.hasMoreElements()) {
                                        Productos pro = (Productos) e.nextElement();
                                        PersisProducto pp = new PersisProducto();
                                        pp.setNumero(consecPedido);
                                        pp.setProd(pro.getProducto().getProd());
                                        pp.setCantidad(pro.getCantidad());
                                        pp.setCambios(pro.getCambio());
                                        pp.setProveedor(pro.getProducto().getProv());
                                        Persistencia p = new Persistencia(PERS_DETALLE);
                                        p.save(pp.persist());
                                    }

                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }

                                waiting.showModeless();
                                pedido = null;
                                //ClienteForm cf = new ClienteForm();
                                ClienteForm cf = ClienteForm.getInstance();

                                waiting.dispose();
                                cf.show();
                            }
                        }).start();

                        final PersisSetup pd = Datos.getInstance().getPersisSetup();

                        if (pd != null && pd.isEnvio()) {
                            new Thread(new Runnable() {

                                public void run() {
                                    enviarDatos(pedido, pd);
                                }
                            }).start();
                        }


                    }
                }
            });

            addCommand(new Command("Atrás", res.getImage("bck.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (Dialog.show("¿?", "AL REGRESAR SE PERDERÁN LOS DATOS DEL PEDIDO.\nDESEA CONTINUAR?", "SI", "NO")) {
                        new Thread(new Runnable() {

                            public void run() {
                                waiting.showModeless();
                                pedido = null;
                                //ClienteForm cf = new ClienteForm();
                                ClienteForm cf = ClienteForm.getInstance();
                                waiting.dispose();
                                cf.show();
                            }
                        }).start();

                    }
                }
            });

            addCommand(new Command("add..Producto", res.getImage("add.png")) {

                public void actionPerformed(ActionEvent evt) {
                    ProductoDialog pro = new ProductoDialog();
                    pro.show();
                    prodSelect = pro.getPro_select();
                    if (prodSelect != null) {
                        bt_des.setText(prodSelect.getDes());
                        bt_prec.setText("$ " + prodSelect.getPrecio());
                        tf_cant.requestFocus();
                    } else {
                        bt_des.setText("");
                        bt_prec.setText("");
                        bt_producto.requestFocus();
                    }
                }
            });

            addCommand(new Command("Consultar", res.getImage("adBrowser.png")) {

                public void actionPerformed(ActionEvent evt) {
                    if (pedido != null && pedido.getVp() != null && !pedido.getVp().isEmpty()) {
                        new Thread(new Runnable() {

                            public void run() {
                                new PedidoDialog(pedido).show();
                                pedido.eliminarProds();
                                upadte();
                            }
                        }).start();
                    }

                }
                

            });


            /*bt_producto.getStyle().setBgSelectionColor(0xE6FF00);
            bt_des.getStyle().setBgSelectionColor(0xE6FF00);
            bt_prec.getStyle().setBgSelectionColor(0xE6FF00);
            bt_producto.getStyle().setFgSelectionColor(0x000000,true);
            bt_des.getStyle().setFgSelectionColor(0x000000,true);
            bt_prec.getStyle().setFgSelectionColor(0x000000,true);*/

            getSelectedStyle().setBgColor(0Xff0000, true);

            footer = new Button("%");
            footer.setAlignment(CENTER);
            addComponent(footer);

        } catch (Exception e) {
            Datos.getInstance().addLogs(e.getMessage());
        } finally {
            res = null;
        }
    }

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l = new Label(label);
        Dimension d = l.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        l.setPreferredSize(d);
        //l.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST, l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    protected Container createSub(Component c, Component c2) {
        Container pair = new Container(new GridLayout(1, 2));
        Container pair2 = new Container(new BorderLayout());
        Container pair3 = new Container(new BorderLayout());
        pair2.addComponent(BorderLayout.CENTER, c);
        pair3.addComponent(BorderLayout.CENTER, c2);
        pair.addComponent(pair2);
        pair.addComponent(pair3);
        return pair;
    }

    private Button createButton() {
        Button boton = new Button("") {

            public void startTicker(long delay, boolean rightToLeft) {
                super.startTicker(100, true);
            }
        };

        return boton;
    }

    private void upadte() {
        long gtotal = pedido.getTotalPedido();
        long gcambios = pedido.getTotalCambios();
        lb_graTo.setText(String.valueOf(gtotal));
        lb_totCamb.setText(String.valueOf(gcambios));
        footer.setText(getPorcentaje(gcambios, gtotal) + "%");
        repaint();
    }

    private void enviarDatos(Pedido pedido, PersisSetup pd) {
        StringBuffer pedServer = new StringBuffer();
        Enumeration e = pedido.getVp().elements();
        while (e.hasMoreElements()) {
            Productos pro = (Productos) e.nextElement();
            pedServer.append(pedido.getCliente().getCodigo());
            pedServer.append(SEPA2).append(pro.getProducto().getProd());
            pedServer.append(SEPA2).append(pro.getCantidad());
            pedServer.append(SEPA2).append(pro.getCambio());
            StringBuffer append = pedServer.append(SEPA2).append(this.consecPedido);
            pedServer.append(";");
        }

        pedServer.deleteCharAt(pedServer.length() - 1);
        enviarDatos(pedServer, pd, "1");
    }

    /**
     * 
     * @param data
     * @param pd
     * @param fuente 1:desde el pedido al momento de guardar
     *               2:cuando se envia tanto pedido y detalle
     */
    public static void enviarDatos(final StringBuffer data, PersisSetup pd, String fuente) {
        //POR EL DISEÑO PD NO PUEDE SER NULO
        Hashtable params = new Hashtable();
        params.put("Juser", pd.getUser());
        //params.put("Jpass", Rot13.encrip("javier"));
        params.put("Jpass", pd.getPass());
        params.put("proc", "save");
        params.put("fte", fuente);
        
        Hashtable files = new Hashtable();
        files.put("file1", new FileInfo(NOM_ARC_DETALLE, "detalle", "text/plain", data.toString().getBytes()));

        HttpMultipartRequest req;
        String mensaje = "";
        try {
            req = new HttpMultipartRequest(pd.getUrl_server(), params, files);
            byte[] response = req.send();
            mensaje = new String(response);

        } catch (Exception ex) {
            mensaje = "Error: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (!mensaje.equals("OK")) {
                Datos.getInstance().addLogs(mensaje);
            }
        }




    }

    private String getPorcentaje(long n, long d) {
        String resp = "0";
        try {
            float porc = 0;
            if (d != 0) {
                porc = (new Float(n).floatValue() / new Float(d).floatValue()) * 100;
            }
            resp = String.valueOf(porc);
            resp = resp.length() > 6 ? resp.substring(0, 7) : resp;

        } catch (Exception e) {
            resp = "NO SOPORTA PUNTO FLOTANTE";
        }
        return resp;


    }
}
